package com.gobang.gobang;

import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.io.IOException;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class GobangController {

    
    @FXML private Canvas gameCanvas;
    @FXML private Label statusLabel;
    @FXML private Button surrenderButton;
    @FXML private Button restartButton;
    @FXML private Button exitButton;
    @FXML private Label scoreLabel;  // 添加比分标签

    private static final int BOARD_SIZE = 15;
    private static final int CELL_SIZE = 40;
    private static final int PIECE_RADIUS = 15;
    private static final int BOARD_PADDING = 20;  // 棋盘边距
    
    private GameBoard gameBoard;
    private NetworkManager networkManager;
    private boolean isMyTurn = false;
    private boolean isBlackPlayer = false;
    
    @FXML
    public void initialize() {

        gameBoard = new GameBoard(BOARD_SIZE);
        
        // 初始化UI状态
        surrenderButton.setDisable(true);
        restartButton.setDisable(true);
        
        // 设置Canvas大小包含边距
        gameCanvas.setWidth((BOARD_SIZE - 1) * CELL_SIZE + BOARD_PADDING * 2);
        gameCanvas.setHeight((BOARD_SIZE - 1) * CELL_SIZE + BOARD_PADDING * 2);
        
        gameCanvas.setOnMouseClicked(this::handleCanvasClick);
        
        // 确保窗口大小合适
        Platform.runLater(() -> {
            Stage stage = (Stage) gameCanvas.getScene().getWindow();
            stage.sizeToScene();
            stage.setMinWidth(900);  // 增大最小宽度
            stage.setMinHeight(800); // 增大最小高度
        });
        
        drawBoard();
    }
    
    private void drawBoard() {
        GraphicsContext gc = gameCanvas.getGraphicsContext2D();
        gc.clearRect(0, 0, gameCanvas.getWidth(), gameCanvas.getHeight());
        
        // 绘制棋盘背景
        gc.setFill(Color.BURLYWOOD);
        gc.fillRect(0, 0, gameCanvas.getWidth(), gameCanvas.getHeight());
        
        // 绘制外边框
        gc.setStroke(Color.BLACK);
        gc.setLineWidth(2);
        gc.strokeRect(BOARD_PADDING, BOARD_PADDING, 
                     (BOARD_SIZE - 1) * CELL_SIZE, 
                     (BOARD_SIZE - 1) * CELL_SIZE);
        
        // 绘制棋盘网格
        gc.setLineWidth(1);
        for (int i = 0; i < BOARD_SIZE; i++) {
            double pos = BOARD_PADDING + i * CELL_SIZE;
            gc.strokeLine(pos, BOARD_PADDING, pos, BOARD_PADDING + (BOARD_SIZE - 1) * CELL_SIZE);
            gc.strokeLine(BOARD_PADDING, pos, BOARD_PADDING + (BOARD_SIZE - 1) * CELL_SIZE, pos);
        }
        
        // 绘制天元和星位
        int[] starPoints = {3, 7, 11};
        for (int i : starPoints) {
            for (int j : starPoints) {
                gc.setFill(Color.BLACK);
                double x = BOARD_PADDING + i * CELL_SIZE;
                double y = BOARD_PADDING + j * CELL_SIZE;
                gc.fillOval(x - 3, y - 3, 6, 6);
            }
        }
        
        // 绘制棋子
        for (int i = 0; i < BOARD_SIZE; i++) {
            for (int j = 0; j < BOARD_SIZE; j++) {
                if (gameBoard.getPiece(i, j) != null) {
                    double x = BOARD_PADDING + i * CELL_SIZE;
                    double y = BOARD_PADDING + j * CELL_SIZE;
                    
                    // 绘制棋子阴影
                    gc.setFill(Color.rgb(0, 0, 0, 0.3));
                    gc.fillOval(x - PIECE_RADIUS + 2, y - PIECE_RADIUS + 2,
                              PIECE_RADIUS * 2, PIECE_RADIUS * 2);
                    
                    // 绘制棋子
                    gc.setFill(gameBoard.getPiece(i, j) ? Color.BLACK : Color.WHITE);
                    gc.fillOval(x - PIECE_RADIUS, y - PIECE_RADIUS,
                              PIECE_RADIUS * 2, PIECE_RADIUS * 2);
                    
                    // 为白色棋子添加边框
                    if (!gameBoard.getPiece(i, j)) {
                        gc.setStroke(Color.BLACK);
                        gc.strokeOval(x - PIECE_RADIUS, y - PIECE_RADIUS,
                                    PIECE_RADIUS * 2, PIECE_RADIUS * 2);
                    }
                }
            }
        }
    }
    
    private void handleCanvasClick(MouseEvent event) {
        if (!isMyTurn || networkManager == null) {
            return;
        }
        
        // 计算棋盘坐标（考虑边距）
        int x = (int) ((event.getX() - BOARD_PADDING + CELL_SIZE/2) / CELL_SIZE);
        int y = (int) ((event.getY() - BOARD_PADDING + CELL_SIZE/2) / CELL_SIZE);
        
        if (x >= 0 && x < BOARD_SIZE && y >= 0 && y < BOARD_SIZE) {
            if (gameBoard.placePiece(x, y, isBlackPlayer)) {
                drawBoard();
                networkManager.sendMessage("MOVE|" + x + "," + y);
                isMyTurn = false;
                statusLabel.setText("等待对手...");
                checkGameStatus();
            }
        }
        
        gameCanvas.requestFocus();
    }
    
    @FXML
    private void handleSurrender() {
        if (networkManager != null) {
            networkManager.sendMessage("MOVE|SURRENDER");
            endGame(false);
        }
    }
    
    @FXML
    private void handleRestart() {
        if (networkManager != null) {
            // 重置游戏状态
            gameBoard = new GameBoard(BOARD_SIZE);
            drawBoard();
            
            // 发送重新开始消息
            networkManager.sendMessage("MOVE|RESTART");
            
            // 等待服务器的游戏开始消息
            statusLabel.setText("等待游戏重新开始...");
            surrenderButton.setDisable(true);
            restartButton.setDisable(true);
        }
    }
    
    public void handleOpponentMove(String move) {
        switch (move) {
            case "SURRENDER":
                endGame(true);  // 对手投降，我赢了
                return;
            case "RESTART":
                statusLabel.setText("对手请求重新开始...");
                return;
            case "WIN":
                endGame(false);  // 对手发送了胜利消息，说明对手赢了
                return;
            default:
                String[] coordinates = move.split(",");
                int x = Integer.parseInt(coordinates[0]);
                int y = Integer.parseInt(coordinates[1]);
                
                gameBoard.placePiece(x, y, !isBlackPlayer);
                drawBoard();
                isMyTurn = true;
                statusLabel.setText("你的回合");
                
                // 检查对手的这步棋是否导致胜利
                if (gameBoard.checkWin()) {
                    // 如果对手这步棋导致胜利，对手赢了
                    endGame(false);
                }
        }
    }
    
    private void checkGameStatus() {
        if (gameBoard.checkWin()) {
            // 当前玩家刚下完棋，如果检测到胜利，说明当前玩家赢了
            if (networkManager != null) {
                networkManager.sendMessage("MOVE|WIN|" + (isBlackPlayer ? "BLACK" : "WHITE"));
            }
            endGame(true);  // 当前玩家赢了
        }
    }
    
    private void endGame(boolean isWinner) {
        isMyTurn = false;
        surrenderButton.setDisable(true);
        restartButton.setDisable(false);  // 启用重新开始按钮
        statusLabel.setText(isWinner ? "你赢了！" : "你输了！");
    }
    
    public void setFirstMove(boolean isFirst) {
        isBlackPlayer = isFirst;
        isMyTurn = isFirst;  // 黑棋先手
        
        // 重置游戏状态
        gameBoard = new GameBoard(BOARD_SIZE);
        drawBoard();
        
        // 更新UI状态
        surrenderButton.setDisable(false);
        restartButton.setDisable(false);
        
        // 更新状态文本
        if (isFirst) {
            statusLabel.setText("游戏开始，你是黑棋，请落子");
        } else {
            statusLabel.setText("游戏开始，你是白棋，等待对手落子");
        }
        
        // 请求当前比分
        networkManager.sendMessage("GET_SCORE");
    }
    
    public void setStatusText(String text) {
        statusLabel.setText(text);
    }
    
    public void setNetworkManager(NetworkManager networkManager) {
        this.networkManager = networkManager;
        networkManager.setGameController(this);
        // 启用游戏相关按钮
        surrenderButton.setDisable(false);
        restartButton.setDisable(false);
        // 请求当前比分
        networkManager.sendMessage("GET_SCORE");
    }
    
    @FXML
    private void handleExit() {
        if (networkManager != null) {
            networkManager.sendMessage("LEAVE_ROOM");
            // 关闭游戏窗口，返回房间列表
            openRoomListWindow();
            // 关闭当前窗口
            ((Stage) gameCanvas.getScene().getWindow()).close();
        }
    }
    
    private void openRoomListWindow() {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource("room-list-view.fxml"));
            Scene scene = new Scene(loader.load(), 800, 600);
            Stage stage = new Stage();
            stage.setTitle("五子棋 - 房间列表");
            stage.setScene(scene);
            
            // 获取控制器并触发连接按钮点击
            RoomListController controller = loader.getController();
            controller.handleConnect();  // 改用新的方法名
            
            stage.show();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public void handleOpponentLeft() {
        Platform.runLater(() -> {
            statusLabel.setText("对手已退出房间");
            isMyTurn = false;
            surrenderButton.setDisable(true);
            restartButton.setDisable(true);
        });
    }
    
    public void setScore(String score) {
        Platform.runLater(() -> {
            if (scoreLabel != null) {
                if (isBlackPlayer) {
                    scoreLabel.setText("比分 " + score);  // 黑方看到的比分
                } else {
                    // 白方看到的比分需要翻转
                    String[] scores = score.split("-");
                    scoreLabel.setText("比分 " + scores[1] + "-" + scores[0]);
                }
            }
        });
    }
} 